package com.tsunami.message.service.impl;

import com.tsunami.message.common.Constant;
import com.tsunami.message.common.JsonUtil;
import com.tsunami.message.common.MessageHelper;
import com.tsunami.message.common.MqConstant;
import com.tsunami.message.entity.Mail;
import com.tsunami.message.entity.MsgLog;
import com.tsunami.message.service.IMsgLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @author lx
 * @since 2024-09-19
 */
@Service
public class ProduceService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IMsgLogService msgLogService;

    /**
     * 发送消息
     *
     * @param mail
     * @return
     */
    public boolean sendByAck(Mail mail) {
        // 创建uuid
        String msgId = UUID.randomUUID().toString().replaceAll("-", "");
        mail.setMsgId(msgId);

        // 发送消息到mq服务器中（附带消息ID）
        CorrelationData correlationData = new CorrelationData(msgId);
        rabbitTemplate.convertAndSend(MqConstant.MAIL_EXCHANGE_NAME, MqConstant.MAIL_ROUTING_KEY_NAME, MessageHelper.objToMsg(mail), correlationData);
        return true;
    }


    /**
     * 发送消息
     *
     * @param mail
     * @return
     */
    public boolean sendByAuto(Mail mail) {
        String msgId = UUID.randomUUID().toString().replaceAll("-", "");
        mail.setMsgId(msgId);
        MsgLog msgLog = new MsgLog();
        msgLog.setMsgId(msgId);
        msgLog.setExchange(MqConstant.MAIL_EXCHANGE_NAME);
        msgLog.setRouteKey(MqConstant.MAIL_ROUTING_KEY_NAME);
        msgLog.setQueueName(MqConstant.MAIL_QUEUE_NAME);
        msgLog.setMsg(JsonUtil.objToStr(mail));
        msgLog.setStatus(Constant.WAIT);
        msgLog.setTryCount(0);
        msgLog.setNextTryTime(LocalDateTime.now().plusMinutes(1));
        msgLog.setCreateTime(LocalDateTime.now());
        msgLog.setUpdateTime(LocalDateTime.now());

        // 1.存储要消费的数据
        msgLogService.insert(msgLog);

        // 2.发送消息到mq服务器中（附带消息ID）
        CorrelationData correlationData = new CorrelationData(msgId);
        rabbitTemplate.convertAndSend(MqConstant.MAIL_EXCHANGE_NAME, MqConstant.MAIL_ROUTING_KEY_NAME, MessageHelper.objToMsg(mail), correlationData);
        return true;
    }
}
